/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MainHuaTiDetailActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-23 下午4:14:18   
 * @version V1.0     
 */
package com.jiyi.activity.main;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.zone.PersonInfoActivity;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.jiyi.bean.main.TopicCatBean;
import com.jiyi.bean.zone.Topic;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.event.TopicListEvent;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.GlideUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: MainHuaTiDetailActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-23 下午4:14:18
 * 
 */
public class MainHuaTiDetailActivity extends ActivityBase implements OnRefreshListener{

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	TextView tvHuaTiName;
	TextView tvHuaTiJoinNum;
	ImageView ivCover;

	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	@BindView(R.id.mainList)
	RecyclerView mainList;
	private List<Topic> mListData = new ArrayList<Topic>();
	EmptyWrapper adapter;
	
	String topic;
	TopicCatBean mTopicCatBean;
	LayoutInflater inflater;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_huati_detail);
		ButterKnife.bind(this);
		this.inflater = LayoutInflater.from(this);
		getIntentData();
		setTop();
		setAdapter();
		onRefresh();
		EventBus.getDefault().register(this);
	}
	
	@Subscribe
	public void onTopicListEvent(TopicListEvent topicListEvent) {
		int type = topicListEvent.type;
		switch (type) {
		case TopicListEvent.MAIN_TOPIC_FRAGMENT:
			onRefresh();
			break;

		default:
			break;
		}
	}
	
	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-23
	 */
	private void getIntentData() {
		String topicCatGson = getIntent().getStringExtra("topicCatBean");
		mTopicCatBean = new Gson().fromJson(topicCatGson, TopicCatBean.class);
		topic = getIntent().getStringExtra("topic");
	}

	private void setTop() {
		tvBack.setText("");
		tvTitle.setText(mTopicCatBean.getName());
		tvSearch.setVisibility(View.INVISIBLE);
	}
	
	private void setAdapter() {
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);
		// 设置布局管理器
		mainList.setLayoutManager(new LinearLayoutManager(this));
		// 添加分割线
		mainList.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, getResources()
						.getDrawable(R.drawable.drvice_10)));
		// 初始化适配器
		CommonAdapter mCommonAdapter = new CommonAdapter<Topic>(this, R.layout.item_jiyouxiu,
				mListData) {
			@Override
			protected void convert(ViewHolder holder, final Topic t,
					final int position) {
holder.setOnClickListener(R.id.ivLogo, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),PersonInfoActivity.class);
						intent.putExtra("id", t.getUser_id());
						startActivity(intent);
						
					}
				});
				holder.setText(R.id.tvUserName, t.getUser_name());
				holder.setText(R.id.tvCreateDate, t.getCreate_time());
				if (TextUtils.isEmpty(t.getContent())) {
					holder.setVisible(R.id.tvContent, false);
				} else {
					holder.setVisible(R.id.tvContent, true);
					if (!TextUtils.isEmpty(t.getAct_name()) && !t.getContent().contains("#"+t.getAct_name()+"#")) {
						t.setContent("#"+t.getAct_name()+"#"+t.getContent());
						holder.setTopicText(R.id.tvContent, t);
					}
					else
					{
						holder.setTopicText(R.id.tvContent, t);
					}
					
				}

				
				holder.setImage(R.id.ivLogo, t.getUser_logo());

				if (t.getImage() == null || t.getImage().size() <= 0) {
					holder.setVisible(R.id.gvXiu, false);
				} else {
					holder.setVisible(R.id.gvXiu, true);
					holder.setAdapter(R.id.gvXiu, t.getImage());
				}
				
				//判断点赞数是否大于0 大于0就显示心+数字，小雨零就不显示数字
				if (t.getLikeNum() > 0) {
					holder.setVisible(R.id.tvGoodNum, true);
					holder.setText(R.id.tvGoodNum, t.getLikeNum() + "");
				}
				else {
					holder.setVisible(R.id.tvGoodNum, false);
				}
				
				//判断心是实心还是空心
				if (t.getFlag().equals("0")) {
					holder.setImageResource(R.id.ivGood, R.mipmap.icon_praise_normal);
				}
				else {
					holder.setImageResource(R.id.ivGood, R.mipmap.icon_praise_on);
				}
				
				holder.setOnClickListener(R.id.rlPraise, new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						praise(t.getId(), position-1,t.getFlag());
					}
				});
			}
		};

		HeaderAndFooterWrapper mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(
				mCommonAdapter);
		View headView = inflater
				.inflate(R.layout.head_detail_topic, null, false);
		headView.setTag("head");
		tvHuaTiName = (TextView) headView.findViewById(R.id.tvHuaTiName); 
		tvHuaTiJoinNum = (TextView) headView.findViewById(R.id.tvHuaTiJoinNum);
		ivCover = (ImageView) headView.findViewById(R.id.ivCover);
		
		tvHuaTiName.setText(mTopicCatBean.getName());
		tvHuaTiJoinNum.setText("参与话题 " + mTopicCatBean.getCount()+ " 人");
		GlideUtil.load(this, mTopicCatBean.getImage(), ivCover);
		mHeaderAndFooterWrapper.addHeaderView(headView);
		
		adapter = new EmptyWrapper(mHeaderAndFooterWrapper);
		adapter.setEmptyView(R.layout.empty_view);
		
		mainList.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@OnClick({ R.id.tvBack,R.id.bottom })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.bottom:
			Intent intent = new Intent(MainHuaTiDetailActivity.this,HuaTiFaBuActivity.class);
			intent.putExtra("topicCatBean", new Gson().toJson(mTopicCatBean));
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		getData(mTopicCatBean.getId());
	}
	
	/**
	 * @author: HYM
	 * @Title: getData
	 * @Description: TODO(获取话题分类数据) void
	 * @date: 2017-7-22
	 */
	private void getData(String id) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);

		VolleyRequest.StringRequestPost(this,
				WebApi.MAIN_TOPIC_DETAIL_LIST, "", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								JSONObject dataJson = new JSONObject(data);
								String topicJson = dataJson
										.getString("topicList");
								List<Topic> temp = new Gson().fromJson(
										topicJson,
										new TypeToken<List<Topic>>() {
										}.getType());
								mListData.clear();
								mListData.addAll(temp);
								adapter.notifyDataSetChanged();

							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	void praise(String id,final int position,String flag) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		params.put("flag", flag);
		VolleyRequest.StringRequestPost(this, WebApi.MAIN_TOPIC_PRAISE, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								String data = obj.getString("data");
								JSONObject dataJson = new JSONObject(data);
								String praiseNum = dataJson.getString("likeNum");
								String flag = dataJson.getString("flag");
								mListData.get(position).setFlag(flag);
								mListData.get(position).setLikeNum(Integer.parseInt(praiseNum));
								//获取返回 的点赞数和是否点赞标志，然后局部刷新
//								adapter.notifyItemChanged(position,mListData.size());
								adapter.notifyDataSetChanged();
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
}
